/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: DepthViewFragment.java
 *   @Date: 18-11-29 下午4:05
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.kline.ui;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.bhex.depth.DepthData;
import com.bhex.depth.DepthView;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;

import io.bhex.app.R;
import io.bhex.app.base.BaseFragment;
import io.bhex.app.utils.ShareConfigUtils;
import io.bhex.app.utils.SkinColorUtil;
import io.bhex.baselib.constant.AppData;
import io.bhex.baselib.images.CImageLoader;
import io.bhex.sdk.UrlsConfig;
import io.bhex.sdk.config.bean.ShareConfigBean;
import io.bhex.sdk.data_manager.SymbolDataManager;
import io.bhex.sdk.quote.bean.DepthDataBean;
import io.bhex.app.kline.presenter.DepthViewPresenter;
import io.bhex.sdk.quote.bean.CoinPairBean;
import io.bhex.baselib.utils.DebugLog;

/**
 * ================================================
 * 描   述：深度图
 * ================================================
 */

public class DepthViewFragment extends BaseFragment<DepthViewPresenter, DepthViewPresenter.DepthViewUI> implements DepthViewPresenter.DepthViewUI, View.OnClickListener {
    private DepthView depthView;
    private String symbol;
    private String exchangeId;
    private String mergeDigitsStr;
    private CoinPairBean mCoinPairBean;
    private String basePrecision;
    private String quotePrecision;
    private int digitBase;
    private int digitPrice;
    private ImageView waterMarkIcon;

    @Override
    protected DepthViewPresenter.DepthViewUI getUI() {
        return this;
    }

    @Override
    protected DepthViewPresenter createPresenter() {
        return new DepthViewPresenter();
    }

    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_depth_layout, null, false);
    }

    @Override
    protected void initViews() {
        super.initViews();
        depthView = viewFinder.find(R.id.depth_view);
        Bundle arguments = getArguments();
        if (arguments != null) {
            symbol = arguments.getString(AppData.INTENT.SYMBOLS);
            exchangeId = arguments.getString(AppData.INTENT.EXCHANGE_ID);
            mergeDigitsStr = arguments.getString(AppData.INTENT.MERGE_DIGITS);
//            getPresenter().requestDepthData(symbol,100);

            mCoinPairBean = (CoinPairBean) arguments.getSerializable(AppData.INTENT.COINPAIR);
            if (mCoinPairBean != null) {
                basePrecision = mCoinPairBean.getBasePrecision();
                quotePrecision = mCoinPairBean.getQuotePrecision();
                String baseToken = mCoinPairBean.getBaseTokenId();
                String quoteToken = mCoinPairBean.getQuoteTokenId();
                digitBase = SymbolDataManager.GetInstance().getTokenDigitBySymbolIdAndTokenId(symbol+baseToken);
                digitPrice = SymbolDataManager.GetInstance().getTokenDigitBySymbolIdAndTokenId(symbol+quoteToken);

            }
        }

        //水印logo
        waterMarkIcon = viewFinder.imageView(R.id.icon);
        ShareConfigBean shareConfig = ShareConfigUtils.getShareConfig();
        setWaterMarkIcon(shareConfig);
    }

    /**
     * 设置水印
     * @param shareConfig
     */
    public void setWaterMarkIcon(ShareConfigBean shareConfig) {
        if (shareConfig != null) {
            String watermarkImageUrl = shareConfig.getWatermarkImageUrl();
            if (!TextUtils.isEmpty(watermarkImageUrl)) {
                viewFinder.find(R.id.name).setVisibility(View.GONE);
                viewFinder.find(R.id.domain).setVisibility(View.GONE);
                CImageLoader.getInstance().load(waterMarkIcon,watermarkImageUrl);
                return;
            }
        }
    }

    @Override
    protected void addEvent() {
        super.addEvent();
        viewFinder.find(R.id.btn_add).setOnClickListener(this);
        viewFinder.find(R.id.btn_add_right).setOnClickListener(this);
        viewFinder.find(R.id.btn_add_scale).setOnClickListener(this);
        viewFinder.find(R.id.btn_reduce_scale).setOnClickListener(this);
    }

    @Override
    public void onStart() {
        super.onStart();

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_add:
                Random random = new Random();
                DepthData.DepthItem depthItem = new DepthData.DepthItem();
                depthItem.setyData(random.nextInt(500));
                depthItem.setxData(random.nextInt(300));
                depthView.addLeftData(depthItem);
                break;
            case R.id.btn_add_right:
                Random random1 = new Random();
                DepthData.DepthItem depthItem1 = new DepthData.DepthItem();
                depthItem1.setyData(random1.nextInt(300));
                depthItem1.setxData(random1.nextInt(400));
                depthView.addRightData(depthItem1);
                break;
            case R.id.btn_add_scale:
                depthView.setScale(depthView.getScale() + 0.05f);
                break;
            case R.id.btn_reduce_scale:
                depthView.setScale(depthView.getScale() - 0.05f);
                break;
        }

    }


    private void addTestData() {

//        depthView.setScale(0.8f);//设置绘制数据占整个画布的高度比例
        float num = 600f;
        float xnum = 10f;
        int lines = 50;
        for (int i = 0; i < lines; i++) {
            DepthData.DepthItem depthItem = new DepthData.DepthItem();
            Random random = new Random();
//            depthItem.setHeight(random.nextInt(300));
            num = num - random.nextInt(15);
            depthItem.setyData(num > 0 ? num : 0);
            xnum = xnum + random.nextInt(5);
            depthItem.setxData(xnum);
            depthView.addLeftData(depthItem);
        }

        float num2 = 3f;
        float xnum2 = xnum + 4;
        int lines2 = 50;
        for (int i = 0; i < lines2; i++) {
            DepthData.DepthItem depthItem = new DepthData.DepthItem();
            Random random = new Random();
//            depthItem.setHeight(random.nextInt(300));
            depthItem.setyData(num2);
            depthItem.setxData(xnum2);
            num2 = num2 + random.nextInt(30);
            xnum2 = xnum2 + random.nextInt(6);
            depthView.addRightData(depthItem);
        }
        depthView.setDecimalDigits(3, 0);
    }

//    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void showDepthView(DepthDataBean data) {
        depthView.setDecimalDigits(digitPrice, digitBase);
        depthView.setScale(0.9f);
        List<DepthData.DepthItem> depthLeftItems = new ArrayList<>();
        List<DepthData.DepthItem> depthRightItems = new ArrayList<>();
        List<List<String>> bids = data.getB();
        //y轴数据需要累加 买盘
        //买盘数据 价格由大到小
        float volumeL = 0;
//        for (List<String> bid : bids) {
//            if (bid.size()>=2) {//验证过滤 保证数据的完整性
//                DepthData.DepthItem depthItem = new DepthData.DepthItem();
//                String price = bid.get(0);
//                price = TextUtils.isEmpty(price)?"0":price;
//                depthItem.setxData(Float.valueOf(price));
//                String volume = bid.get(1);
//                volume = TextUtils.isEmpty(volume)?"0":volume;
//                volumeL += Float.valueOf(volume);
//                depthItem.setyData(volumeL);
//                depthLeftItems.add(0,depthItem);//添加到第零位  正序取，反序放
//            }
//
//        }

        for (int i = bids.size() - 1; i >= 0; i--) {
            List<String> bid = bids.get(i);
            if (bid.size() >= 2) {//验证过滤 保证数据的完整性
                DepthData.DepthItem depthItem = new DepthData.DepthItem();
                String price = bid.get(0);
                price = TextUtils.isEmpty(price) ? "0" : price;
                depthItem.setxData(Float.valueOf(price));
                String volume = bid.get(1);
                volume = TextUtils.isEmpty(volume) ? "0" : volume;
                volumeL += Float.valueOf(volume);
                depthItem.setyData(volumeL);
                depthLeftItems.add(0, depthItem);//添加到第零位  正序取，反序放
//                DebugLog.e("DEPTHDATA:", "BID: " + Float.valueOf(price) + " " + volumeL);
            }
        }

//        Collections.reverse(depthLeftItems);
//        for (DepthData.DepthItem depthRightItem : depthLeftItems) {
//            DebugLog.e("DEPTHDATA:","BID sort: "+depthRightItem.getxData()+" "+depthRightItem.getyData());
//        }

        depthView.setLeftData(depthLeftItems);

        List<List<String>> asks = data.getA();
        float volumeR = 0;
        for (List<String> ask : asks) {
            if (ask.size() >= 2) {
                DepthData.DepthItem depthItem = new DepthData.DepthItem();
                String price = ask.get(0);
                price = TextUtils.isEmpty(price) ? "0" : price;
                depthItem.setxData(Float.valueOf(price));
                String volume = ask.get(1);
                volume = TextUtils.isEmpty(volume) ? "0" : volume;
                volumeR += Float.valueOf(volume);
                depthItem.setyData(volumeR);
                depthRightItems.add(depthItem);
//                DebugLog.e("DEPTHDATA:", "ASK: " + Float.valueOf(price) + " " + volumeR);
            }
        }

//        Collections.sort(depthRightItems);
//        for (DepthData.DepthItem depthRightItem : depthRightItems) {
//            DebugLog.e("DEPTHDATA:","ASK sort: "+depthRightItem.getxData()+" "+depthRightItem.getyData());
//        }

        depthView.setRightData(depthRightItems);

//        getActivity().runOnUiThread(()->{
//            depthView.setLeftData(depthLeftItems);
//            depthView.setRightData(depthRightItems);
//        });

    }

    @Override
    public void getDepthDataFailed(String msg) {

    }

    @Override
    public void showDepthView(Map<String, String> mapA, Map<String, String> mapB) {
        ArrayList<DepthData.DepthItem> depthLeftItems = new ArrayList<>();
        ArrayList<DepthData.DepthItem> depthRightItems = new ArrayList<>();
        for (String key : mapA.keySet()) {
            DepthData.DepthItem depthItem = new DepthData.DepthItem();
            depthItem.setxData(Float.valueOf(key));
            depthItem.setyData(Float.valueOf(mapA.get(key)));
            depthLeftItems.add(depthItem);
            DebugLog.e("DEP", key + " " + mapA.get(key));
        }
        depthView.setLeftData(depthLeftItems);

        for (String key : mapB.keySet()) {
            DepthData.DepthItem depthItem = new DepthData.DepthItem();
            depthItem.setxData(Float.valueOf(key));
            depthItem.setyData(Float.valueOf(mapB.get(key)));
            depthRightItems.add(depthItem);
            DebugLog.e("DEP", key + " " + mapB.get(key));
        }
        depthView.setRightData(depthRightItems);

    }
}
